import { inject } from 'vue';
import { languageInjectionKey, communityInjectionKey, tokenInjectionKey } from '../utils/keys';
import { $fetch as $baseFetch, type FetchOptions } from '../utils/fetch';
import { HEADER_KEY_COMMUNITY, HEADER_KEY_LANGUAGE, HEADER_KEY_TOKEN } from '@/common/utils/constants';

export function useFetch() {
  const language = inject(languageInjectionKey) as string;
  const community = inject(communityInjectionKey) as string;
  const token = inject(tokenInjectionKey) as string;

  const headers: Record<string, any> = {
    [HEADER_KEY_COMMUNITY]: community,
    [HEADER_KEY_LANGUAGE]: language,
  }
  token && (headers[HEADER_KEY_TOKEN] = token);

  const $fetch = <ResT = any>(url: string, inputOptions: FetchOptions = {}) => {
    return $baseFetch<ResT>(url, {
      headers,
      ...inputOptions,
    });
  }

  return {
    $fetch,
  };
}
